package org.gdkm.service.impl;


import com.google.common.collect.Lists;
import org.gdkm.domin.TbUser;
import org.gdkm.mapper.TbUserMapper;
import org.gdkm.service.AdminService;
import org.gdkm.util.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import tk.mybatis.mapper.MyMapper;
import tk.mybatis.mapper.entity.Example;
import java.util.List;

@Service
@Transactional
public class AdminServiceImpl extends BaseServiceImpl<TbUser,TbUserMapper> implements AdminService<TbUser> {

    @Autowired
    MyMapper tbUserMapper;

    @Override
    public void register(TbUser tbUser) {
        tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
        System.out.println("tbUser = " + tbUser);
        int i = tbUserMapper.insert(tbUser);
        System.out.println("成功插入数据：i = " + i);
    }

    @Override
    public TbUser login(String username, String password) {
        Example example=new Example(TbUser.class);
        example.createCriteria().andEqualTo("username",username);
        TbUser tbUser = (TbUser) tbUserMapper.selectOneByExample(example);
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (tbUser.getPassword().equals(password)){
            return tbUser;
        }
        return null;
    }

    public BaseResult checklogin(String username,String password){
        BaseResult baseResult = getBaseResult(username, password);
        if (baseResult!=null){
            return baseResult;
        }
        TbUser user = login(username, password);
        if (user!=null){
            return BaseResult.ok(user);
        }
        else {
            return BaseResult.notOk(Lists.newArrayList(new BaseResult.Error("","登陆失败")));
        }

    }
    public static BaseResult getBaseResult(String username, String password) {
        BaseResult baseResult = null;
        List<BaseResult.Error> errors = Lists.newArrayList();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            baseResult= BaseResult.notOk(Lists.newArrayList(
                    new BaseResult.Error("username", "账号不能为空"),
                    new BaseResult.Error("password", "密码不能为空")
            ));

        }
        return baseResult;
    }
}
